<template>
  <div class="release">
    <div class="release-box">
      <div class="release-top">
        <span @click="handleCancel">取消</span>
        <div class="release-top-center">发布动态</div>
        <button style="float: right" @click="gotofabu">发布</button>
      </div>
      <div class="release-botton">
        <van-cell-group inset>
          <van-field
            v-model="titleValue"
            placeholder="请输入标题"
            label-align="top"
        /></van-cell-group>
        <van-cell-group inset>
          <van-field
            v-model="message"
            rows="5"
            autosize
            type="textarea"
            maxlength="200"
            placeholder="有什么运动趣事，说说看..."
            show-word-limit
          />
        </van-cell-group>
        <van-field name="uploader">
          <template #input>
            <van-uploader v-model="contextvalue" @click="startStreaming" />
          </template>
        </van-field>
        <video ref="videoElement" autoplay playsinline></video>
        <button @click="router.push('/img')">拍照按钮</button>
        <button v-if="position == null">
          <van-icon name="location-o" />正在获取
        </button>
        <button v-else @click="handleClick">
          <van-icon name="location-o" />添加位置
        </button>
        <p v-if="address">{{ `当前位置：${address}` }}</p>
        <p v-else>正在获取当前位置...</p>
        <div v-if="shouldShowPanel">
          <van-floating-panel
            :height="panelHeight"
            class="custom-floating-panel"
          >
            <div
              class="panel-content"
              style="text-align: center; padding: 15px"
              v-for="item in popularTalk"
              :key="item"
              @click="addTag(item)"
            >
              <b><van-icon name="fire-o" color="#ee0a24" /> #{{ item }}#</b>
            </div>
          </van-floating-panel>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import axios from "axios";
import { ref, reactive, onMounted, computed } from "vue";
import "./release.css";
import { showSuccessToast, showFailToast } from "vant";
import { useRouter } from "vue-router";
import { showConfirmDialog } from "vant";
import { flat } from "vant/lib/utils";
const show = ref(false);
const router = useRouter();
const contextvalue = ref([]);
const titleValue = ref("");
const message = ref("");
const aaaaa = ref("");
const videoElement = ref(null);
let stream = null;

// 发布
const gotofabu = async () => {
  if (titleValue.value == "" || message.value == "") {
    showConfirmDialog({
      title: "提示",
      message: "请输入标题和内容",
    });
  } else {
    const data = {
      title: titleValue.value,
      content: message.value,
      img: contextvalue.value,
      location: address.value,
    };
    console.log(data);
    const res = await axios.post("http://8.130.46.189:3000/ljb/addfb", data);
    console.log(res);
    if (res.status == 200) {
      showSuccessToast("发布成功");
      router.push("/trends");
    } else {
      showFailToast("发布失败");
    }
  }
};

// 取消
const goto = () => {
  router.push("/ljb/trends");
};

const popularTalk = ref([
  "每日打卡",
  "运动趣事",
  "运动小知识",
  "运动装备",
  "校园夜跑",
  "运动健身",
  "释放压力",
  "运动小技巧",
]);
const panelHeight = ref(0); // 初始高度设置为0或者你想要的默认值

//获取位置
// 坐标
const position = ref(null);
// 位置
const address = ref("");

const handleClick = async () => {
  if (position.value) {
    const { latitude, longitude } = position.value;
    console.log(`经度：${longitude}，纬度：${latitude}`);
    const response = await axios.get(
      `https://restapi.amap.com/v3/geocode/regeo?&location=${longitude},${latitude}&key=bb011fe314e2d7bac80b6b6084b94374`
    );
    if (
      response.data &&
      response.data.regeocode &&
      response.data.regeocode.addressComponent
    ) {
      const { city, district } = response.data.regeocode.addressComponent;
      address.value = `${city}${district}`;
    }
  }
};

onMounted(async () => {
  if (localStorage.getItem("content")) {
    message.value = localStorage.getItem("content");
  }
  if (localStorage.getItem("title")) {
    titleValue.value = localStorage.getItem("title");
  }

  if (navigator.geolocation) {
    try {
      const positionInfo = await new Promise((resolve, reject) => {
        navigator.geolocation.getCurrentPosition(
          (pos) => {
            resolve(pos.coords);
          },
          (err) => {
            reject(err);
            console.error("获取位置失败:", err);
          }
        );
      });
      position.value = {
        latitude: positionInfo.latitude.toFixed(6),
        longitude: positionInfo.longitude.toFixed(6),
      };
    } catch (error) {
      console.error("获取位置失败:", error);
    }
  } else {
    console.log("此浏览器不支持地理位置");
  }
  //
  if (localStorage.getItem("content") || localStorage.getItem("title")) {
    message.value = localStorage.getItem("content");
    titleValue.value = localStorage.getItem("title");
  }
  // const windowHeight = window.innerHeight;
  const anchors = [500, window.innerWidth * 0.6];
  panelHeight.value = anchors[0]; // 初始设置为第一个 anchor 值

  if (stream) {
    stream.getTracks().forEach((track) => track.stop());
    stream = null;
  }
});

function addTag(tag) {
  showPanel.value = false;
  if (!message.value.includes("#" + tag)) {
    message.value += (message.value ? " #" : "") + tag;
  }
}
const showPanel = ref(true); // 控制浮动面板显示状态的变量

const shouldShowPanel = computed(() => {
  return message.value.endsWith("#");
  // console.log(1);
});

//取消
const showSavePrompt = ref(false);
const handleCancel = () => {
  showSavePrompt.value = true;
  showConfirmDialog({
    message: "内容已更改，是否要保存再退出？",
  })
    .then(() => {
      localStorage.setItem("content", message.value);
      localStorage.setItem("title", titleValue.value);
      console.log(111);
      router.go(-1);
    })

    .catch(() => {
      message.value = "";
      titleValue.value = "";
      localStorage.setItem("content", message.value);
      localStorage.setItem("title", titleValue.value);
      router.go(-1);
    });
};

async function startStreaming() {
  try {
    const constraints = {
      video: true,
      audio: true, // 如果你不需要音频，可以设置为false
    };

    stream = await navigator.mediaDevices.getUserMedia(constraints);
    videoElement.value.srcObject = stream;
  } catch (err) {
    console.error("Error accessing the media stream: ", err);
  }
}
</script>

<style lang="scss" scoped></style>
